﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ExtractDeleteRename
{
    class Program
    {
        const string BASE_DIRECTORY = @"C:\Users\Bommel\Downloads\Videos\DragonballZ\";
        const string EPISODES_FILE = @"DragonballZ.csv";
        const string SEVEN_ZIP_EXE = @"c:\Program Files\7-Zip\7z.exe";

        static Dictionary<int, string> _dicEpisodeNames = new Dictionary<int, string>();



        static void Main(string[] args)
        {
            //first step: read episodes
            if (_readEpisodesFile())
            {
                //next step:
                if (_handleArchives())
                {
                    //next step:

                }
            }

            Console.Write("press any key...");
            Console.ReadKey();
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        static bool _handleArchives()
        {
            Console.WriteLine("Handling archives:");

            //Break condition
            int i = 0;

            string[] strArchives = Directory.GetFiles(BASE_DIRECTORY, "*.rar");
            foreach (string strArchive in strArchives)
            {
                Console.WriteLine("   " + strArchive);

                //extract file
                using (Process p1 = new Process())
                {
                    ProcessStartInfo psi = new ProcessStartInfo();
                    psi.FileName = SEVEN_ZIP_EXE;
                    psi.Arguments = "e \"" + strArchive + "\" -o\"" + BASE_DIRECTORY + "\"";

                    p1.StartInfo = psi;
                    p1.Start();
                    p1.WaitForExit();
                    while (!p1.HasExited) { }

                    Console.WriteLine("   Extracting done...");
                }

                //get fileinfos of extracted file
                FileInfo fi = new FileInfo(strArchive);
                string strEpisodeNr = fi.Name.Split('.')[0];
                fi = null;
                string strMkvFile = BASE_DIRECTORY + strEpisodeNr + ".mkv";
                string strNewMkvFile = strEpisodeNr + "_" + _dicEpisodeNames[int.Parse(strEpisodeNr)] + ".mkv";
                Console.WriteLine("   Old Name: " + strMkvFile);
                Console.WriteLine("   New Name: " + strNewMkvFile);

                Thread.Sleep(1000);

                //rename file
                if (File.Exists(strMkvFile))
                {
                    using (Process p2 = new Process())
                    {
                        ProcessStartInfo psi = new ProcessStartInfo();
                        psi.FileName = "cmd.exe";
                        psi.Arguments = "/C ren " + strMkvFile + " " + strNewMkvFile;
                        psi.UseShellExecute = false;    
                        psi.RedirectStandardOutput= true;

                        p2.StartInfo = psi;
                        p2.Start();

                        using (StreamReader srOutput = p2.StandardOutput)
                        {
                            string strResult = srOutput.ReadToEnd();
                            //Console.WriteLine(strResult);
                        }

                        p2.WaitForExit();
                        while (!p2.HasExited) { }

                        Console.WriteLine("Renamed file...");
                    }
                }

                //Break condition
                i++;
                //if (i >= 3) break;
            }

            return true;
        }



        /// <summary>
        /// reads file containing episodes names
        /// </summary>
        /// <returns></returns>
        static bool _readEpisodesFile()
        {
            Console.WriteLine("Reading Episode Names ...");

            string strFileName = string.Concat(BASE_DIRECTORY, EPISODES_FILE);
            if (!File.Exists(strFileName))
            {
                Console.WriteLine("Episodes file not found.");
                return false;
            }

            _dicEpisodeNames.Clear();

            using (StreamReader sr = new StreamReader(strFileName, Encoding.Default))
            {
                string strLine = "";
                while (!sr.EndOfStream)
                {
                    try
                    {
                        strLine = sr.ReadLine();
                        string[] strParts = strLine.Split(';');
                        _dicEpisodeNames.Add(int.Parse(strParts[0]), strParts[1].Replace(' ', '_'));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error reading Episodes. (Line:'" + strLine + "', Message:'" + ex.Message + "')");
                    }
                }
            }

            Console.WriteLine("Done reading Episodes (" + _dicEpisodeNames.Count + ")");

            return true;
        }
    }
}